import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, message, Tag, Divider, Modal} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {REG_CODE, TableListItem} from '@/utils/constants';
import {isSuccess, isSuccessful, renderTreeNode} from "@/utils/utils";
import CreateForm from "@/components/CreateForm/CreateForm";
import EditContent from "@/components/EditContent";
import UserDetail from "@/components/UserDetail";
import {OperateSystem, UserManager} from "@/services/api-functions";

const UserList: React.FC = () => {

  const [visible, setVisible] = useState<any>(false);
  const [active, setActive] = useState<any>(false);
  const [visiblePwd, setVisiblePwd] = useState<any>(false);
  const [visibleDetail, setVisibleDetail] = useState<any>(false);
  const actionRef = useRef<any>();
  const [allRoleList, setAllRoleList] = useState<any[]>([]);

  useEffect(() => {
    try {
      queryAllRootList().then()
    } catch (e) {}
  }, [])

  const queryAllRootList = async () =>{
    let {data, code}:any = await OperateSystem.queryAllRootRoleList();
    if(isSuccess(code)){
      setAllRoleList(data.map((node: any) => renderTreeNode(node)))
    }
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '关键词',
      dataIndex: 'keyword',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width:170,
      hideInSearch: true,
      ellipsis: true,
      formItemProps: {rules:[{ required: true}],}
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      width:250,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'cellphone',
      width:170,
      hideInSearch: true,
      ellipsis: true,
      formItemProps: {rules:[{ required: true, pattern: REG_CODE.CELLPHONE, message:'请输入正确的手机号'}],}
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width:250,
      hideInSearch: true,
      ellipsis: true,
      formItemProps: {rules:[{ required: false, pattern: REG_CODE.EMAIL, message:'请输入正确的邮箱'}],}
    },
    {
      title: '角色',
      dataIndex: 'userRoles',
      width:250,
      hideInSearch: true,
      ellipsis: true,
      hideInForm: true,
      render: (_, record: any) => record.userRoles && record.userRoles.length > 0
        ? (record.supperAdmin
          ?[<Tag color='blue'>超级管理员</Tag>, record.userRoles.map((item: any) => <Tag color='#f50'>{item.role.name}</Tag>)]
          :[record.userRoles.map((item: any) => <Tag color='#f50'>{item.role.name}</Tag>)])
        : '暂无角色'
    },
    {
      title: '是否可登录',
      dataIndex: 'loginAdmin',
      width:120,
      valueEnum: {
        true: { text: '可登录', status: 'Success' },
        false: { text: '不可登录', status: 'Error' },
      },
      formItemProps: {rules:[{ required: true}],}
    },
    {
      title: '密码',
      dataIndex: 'password',
      valueType: 'password',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      width:170,
      hideInSearch: true,
      hideInForm: true,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => [
        <a onClick={() => {
          setActive(record)
          setVisibleDetail(true)
        }}>
          详情
        </a>,
        <Divider type="vertical" />,
        (record.supperAdmin ? null : [<a onClick={() => {
          // @ts-ignore
          OperateSystem.changeUserPwd(record.id, !record.loginAdmin).then(response => {
            if (isSuccessful(response)) {
              message.success('修改成功', 1, () => actionRef.current?.reload())
            }
          })
        }}>{record.loginAdmin ? '禁止登录' : '开启登录'}</a>, <Divider type="vertical"/>]),
        <a onClick={() => {
          setActive(record);
          setVisiblePwd(true);
        }}>修改密码</a>,
        (record.supperAdmin ? null : [<Divider type="vertical" />,
          <a style={{color: "red"}} onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要删除 <Tag color='#108ee9'>{record.name}</Tag> 吗？</span>,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
              OperateSystem.deleteDeleteUser(record.id).then(response=>{
                if(isSuccessful(response)){
                  message.success('删除成功', 1, ()=>actionRef.current?.reload())
                }
              })
            } ,
          })}>删除</a>]),
      ],
    },
  ];

  const queryUserList = async (params:any, sorter:any, filter:any) => {

    let {data:{records, total}, code}:any = await UserManager.operateList().queryUserPageable(params);

    return {data:records||[], success: isSuccess(code), total:isSuccess(code)?total:0};
  }

  const createUser = () => <CreateForm onCancel={() => setVisible(false)} title='添加用户' modalVisible={visible}>
    <ProTable<TableListItem, TableListItem>
      onSubmit={async (value: any) => {
        const resp = await OperateSystem.userSaveOrUpdate(value);
        if (isSuccessful(resp)) {
          setVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }}
      rowKey="key"
      type="form"
      columns={columns}
    />
  </CreateForm>;

  const changePwd = () => <CreateForm onCancel={() => setVisiblePwd(false)} title='修改密码' modalVisible={visiblePwd}>
    <ProTable<TableListItem, TableListItem>
      onSubmit={async (value: any) => {
        if (active && value) {
          const resp = await OperateSystem.changeUserPwd(active.id, value.password);
          if (isSuccessful(resp)) {
            setVisiblePwd(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }
      }}
      rowKey="key"
      type="form"
      columns={[
        {
          title: '姓名',
          dataIndex: 'name',
          hideInSearch: true,
          hideInTable: true,
          renderFormItem: ((schema, config) => <span>{active&&active.name}</span>)
        },
        {
          title: '密码',
          dataIndex: 'password',
          valueType: 'password',
          hideInSearch: true,
          hideInTable: true,
          formItemProps: {rules:[{ required: true}]}
        },
      ]}
    />
  </CreateForm>;

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle='用户列表'
        actionRef={actionRef}
        rowKey="uid"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => setVisible(true)}>
            <PlusOutlined /> 添加用户
          </Button>,
        ]}
        request={(params, sorter, filter) => queryUserList(params, sorter, filter)}
        columns={columns}
        scroll={{ x: 1300 }}
      />

      {createUser()}

      {changePwd()}

      <EditContent title={['用户详情', <span>&nbsp;</span>, active ? <Tag color='#108ee9'>{active.name}</Tag> : null]}
                   visible={visibleDetail} onClose={() => setVisibleDetail(false)}>
        <UserDetail user={active} allRoleList={allRoleList} refresh={() => actionRef.current?.reload()}/>
      </EditContent>

    </PageContainer>
  );
};

export default UserList;
